﻿<template id="single_long_text_template">
    <div class="single_long_text_box">
        <div class="single_long_text_max" :style="{'max-height':maxHeight?`${maxHeight}px`:'none'}">
            <div class="single_long_text" :style="{'-webkit-line-clamp':rows,'line-clamp':rows,'height':`${height}px`}" ref="refText">
                <div class="single_long_text_content" ref="refContent" :style="{whiteSpace:preWrap?'pre-wrap':'initial'}">
                    <slot></slot>
                </div>
            </div>
        </div>
        <div v-if="isExceed" class="single_long_text_trigger">
            <span v-on:click="trigger">... {{ moreVisible ? '收起' : '展开更多' }}</span>
            <span v-on:click="preWrap=!preWrap">{{ preWrap ? '不换行': '要换行' }}</span>
        </div>
    </div>
</template>
<script type="text/javascript">
    var single_long_text = {
        template: "#single_long_text_template",
        data() {
            return {
                preWrap: false,
                lineHeight: 0,
                showHeight: 0,
                maxHeight: 0,
                fullHeight: 0,
                height: 0,
                isExceed: false,
                moreVisible: false
            }
        },
        props: ["rows", "maxRows", "wrap"],
        methods: {
            init() {
                var that = this;
                var refText = that.$refs.refText;
                var refContent = that.$refs.refContent;

                that.preWrap = that.wrap || false;
                that.lineHeight = Number(window.getComputedStyle(refText).lineHeight.slice(0, -2));
                that.showHeight = that.lineHeight * (that.rows || 1);
                that.maxHeight = that.lineHeight * (that.maxRows || 0);

                new ResizeObserver((entries) => {
                    for (let entry of entries) {
                        that.fullHeight = entry.contentRect.height;
                        that.isExceed = that.showHeight < that.fullHeight;
                        that.resize();
                    }
                }).observe(refContent);
            },
            trigger() {
                this.moreVisible = !this.moreVisible; this.resize();
            },
            resize() {
                this.height = this.moreVisible ? this.fullHeight + this.lineHeight : this.showHeight;
            }
        },
        mounted() { this.init(); }
    };
</script>